package com.my.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.my.bean.Category;
import com.my.bean.Page;
import com.my.bean.URLSAVE;
import com.my.bean.User;
import com.my.service.CategoryService;
import com.my.test.HtmlRegexpUtil;
import com.my.test.MyUtil;
import com.my.test.test;


// 告诉spring mvc这是一个控制器类
@Controller
@RequestMapping("")
public class CategoryController {
	@Autowired
	CategoryService categoryService;
	
	@RequestMapping("listCategory")
	public ModelAndView listCategory(Page page){
		ModelAndView mav = new ModelAndView();
		List<Category> cs= categoryService.list(page);
		int count = categoryService.getcount();
		page.caculateLast(count);
		// 放入转发参数
		mav.addObject("cs", cs);
		// 放入jsp路径
		mav.setViewName("listCategory");
		return mav;
	}
	
	@RequestMapping("upload")
	public ModelAndView listCategor(String search){
		ModelAndView mav = new ModelAndView();
		// 放入转发参数
		try {
			if (search.equals("")){
				search = "a";
			}
		}catch (NullPointerException e){
			search = "a";
		}

		mav.addObject("cs", search);
		// 放入jsp路径
		mav.setViewName("upload");
		return mav;
	}
	
	@RequestMapping("listCate")
	public ModelAndView listCate(){
		ModelAndView mav = new ModelAndView();
		int cs= categoryService.getcount();
		mav.addObject("cs", cs);
		mav.setViewName("listCate");
		return mav;
	}
	
	@RequestMapping("selectAll")
	public void resultCate(HttpServletResponse response){
		List<Category> cs= categoryService.list();
		MyUtil.writejson(response,cs);
	}

	@RequestMapping("insertText")
	public void insertText(HttpServletResponse response,User c){
		MyUtil.writejson(response,1);
	}
	
	@RequestMapping(value = "uploadMedia", method = RequestMethod.POST)
	public void resultAllurl(@RequestParam("uploadfile")CommonsMultipartFile cmf,HttpServletResponse response,HttpServletRequest request) throws IllegalStateException, IOException{
		
		String uname = request.getParameter("uname");
	    String path = "D:\\" + cmf.getOriginalFilename();
	    File file = new File(path);
	    cmf.transferTo(file);
	    MyUtil.writejson(response,"上传成功");
	}
	
	@RequestMapping("selectallurl")
	public void resultAllurl(HttpServletResponse response){
		List<URLSAVE> cs= categoryService.selectallcontext();
		MyUtil.writejson(response,cs);
	}
	
	@RequestMapping("geturlhref")
	public void getUrlHref(HttpServletResponse response,String path){
		Connection connect = Jsoup.connect(path); 
		connect.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").timeout(13000);
        Document document;
		try {
			document = connect.get();
			String es = document.html();
			List[] arr = test.getHtmlAName(es);
			List list = arr[0];
			List<URLSAVE> list2 = arr[1];
			for (int i = 0; i < list2.size(); i++) {
				URLSAVE u = list2.get(i);
				URLSAVE urlsave = new URLSAVE(u.getUrl_name(),path,u.getUrl_context());
				try {
					URLSAVE ubool = categoryService.selectbycontext(u.getUrl_context());
				if(ubool.getUrl_name().equals("")||ubool.getUrl_parent().equals("")){
				}else{}
				} catch (NullPointerException e) {
					categoryService.addURL(urlsave);
				}
			}
			MyUtil.writejson(response,list);
			System.out.println(list.get(0));
		} catch (IOException e) {
			e.printStackTrace();
			Map map = new HashMap();
			map.put("error", e.getMessage());
			MyUtil.writejson(response,map);
		}
	}

	/**
	 * geturltext 获得链接html里所有文字
	 * @param response
	 * @param path 地址
	 */
	@RequestMapping("geturltext")
	public void getUrlText(HttpServletResponse response,String path){
		Document doc;
		try {
			doc = Jsoup.connect(path).get();
			String es = doc.html();
			String a = HtmlRegexpUtil.zhenzepipei(es, HtmlRegexpUtil.regEx_style);
			String b = HtmlRegexpUtil.zhenzepipei(a, HtmlRegexpUtil.regEx_script);
			String c = HtmlRegexpUtil.zhenzepipei(b, HtmlRegexpUtil.regEx_special);
			String d = HtmlRegexpUtil.filterHtmlhua(HtmlRegexpUtil.replaceBlank(HtmlRegexpUtil.filterHtml(c)));
			System.out.println(d);
			String[] e = d.split("/");
			Map map = new HashMap();
			for(int i=0;i<e.length;i++){
				map.put("map"+i, e[i]);
			}

			MyUtil.writejson(response,map);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping("delete")
	public ModelAndView delete(int id){
		categoryService.delete(id);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
		return mav;
	}

	@RequestMapping("login")
	public void login(HttpServletResponse response,User user){
		User u = categoryService.selectbyname(user.getUsername());
		try {
			if(u.getPassword().equals(user.getPassword())){
				MyUtil.writesuccessjson(response,"login succsess");
			}else{
				MyUtil.writeErrorjson(response,"password error");
			}
		} catch (NullPointerException e) {
			MyUtil.writeErrorjson(response,"input error");
		}
	}

	@RequestMapping("insertuser")
	public void inserUser(HttpServletResponse response,User user){
		try {
			if(user.getUsername().equals("")||user.getPassword().equals("")){
			MyUtil.writeErrorjson(response,"insert error");
		}else{
			categoryService.adduser(user);
			MyUtil.writesuccessjson(response,"insert success");
		}
		} catch (NullPointerException e) {
			MyUtil.writeErrorjson(response,"input error");
		}
	}

	/**
	 * searchurl 搜索
	 * @param response
	 * @param url_name 搜索关键字
	 */
	@RequestMapping("searchurl")
	public void searchurl(HttpServletResponse response,String url_name){
		MyUtil.writejson(response,categoryService.selectallsearch(url_name+"%"));
	}
	
	@RequestMapping("tesst")
	public void dsadsa(HttpServletResponse response){
		init();
		MyUtil.writesuccessjson(response,"insert success");
	}
	
	public void init(){
		List<URLSAVE> list = categoryService.selectallcontext();
		for(int i = 0;i<list.size();i++){
			URLSAVE u = list.get(i);
			String url_p = test.geturr(u.getUrl_parent());
			String url_c = u.getUrl_context().replaceAll(url_p, "");
			if(u.getUrl_context().equals("javascript:void(0)")||u.getUrl_context().equals("javascript:;")||u.getUrl_context().equals("javascript:void(0);")){
				
			}else{
				goall(url_p+url_c);
			}
			
		}
	}
	
	public void goall(String path){
		Connection connect = Jsoup.connect(path); 
		connect.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").timeout(13000);
        Document document;
		try {
			document = connect.get();
			String es = document.html();
			List[] arr = test.getHtmlAName(es);
			List list = arr[0];
			List<URLSAVE> list2 = arr[1];
			for (int i = 0; i < list2.size(); i++) {
				URLSAVE u = list2.get(i);
				URLSAVE urlsave = new URLSAVE(u.getUrl_name(),path,u.getUrl_context());
				try {
					URLSAVE ubool = categoryService.selectbycontext(u.getUrl_context());
				if(ubool.getUrl_name().equals("")||ubool.getUrl_parent().equals("")){
				}else{}
				} catch (NullPointerException e) {
					categoryService.addURL(urlsave);
				}
			}
			System.out.println(list.get(0));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
